require "LingDang"

--LingDang class
GeZi = LingDang:new{
	velocity = nil,
}

function GeZi:onEnter()
	Misc:log("GeZi : onEnter .. " .. Misc:getNodeName(self))
	LingDang.onEnter(self)
	self.collideMusic = "collide_gezi.mp3"
	self.velocity = CCPoint(60, 0)
end

function GeZi:dispear()
	self.velocity.x = self.velocity.x * 10
	self.bDispeared = true
end

function GeZi:collide()
	SimpleAudioEngine:sharedEngine():playEffect(self.collideMusic);
	local cc2dNode = CC2DFileCache:sharedCC2DFileCache():addCC2DNode("baozha.cc2d")
	local ccNode = cc2dNode:createCCNode(self.world)
	local pos = self:getParent():convertToWorldSpace(self:getPositionLua())
	pos = self.world:convertToNodeSpace(pos)
	ccNode:setPosition(pos.x, pos.y)
	--ccNode:setScale(1/self:getScale())
	--local size = self:getContentSize()
	--local anchorPoint = self:getAnchorPoint()
	--ccNode:setPosition(size.width*0.5, size.height*0.5)
	self:dispear()
end

function GeZi:tick(dt)
	local curPos = self:getPositionLua()
	
	local worldPos = self:getParent():convertToWorldSpace(curPos)
	local nodePos = self.factory:getParent():convertToNodeSpace(worldPos)
	
	if not self.bDispeared and ((worldPos.y < -g_winSize.height*0.25) or (nodePos.y < self.minHeight)) then
		LingDang.dispear(self)
	end
	
	if not self.bDispeared then
		if (worldPos.x <= 0) or (worldPos.x >= g_winSize.width) then
			self.velocity.x = -self.velocity.x
		end
	end
	
	local delta = ccpMult(self.velocity, dt)
	curPos = ccpAdd(curPos, delta)
	self:setPosition(curPos.x, curPos.y)
	
	if (self.velocity.x < 0) and (not self:isFlipX()) then
		self:setFlipX(true)
	elseif (self.velocity.x > 0) and (self:isFlipX()) then
		self:setFlipX(false)
	end
end

function GeZi:onExit()
	Misc:log("GeZi : onExit .. " .. Misc:getNodeName(self))
	LingDang.onExit(self)
end

function GeZi:showScore(score)
	self.world.scoreLabel:setString(tostring("双倍分数"))
	self.world.scoreLabel:setOpacity(255)
	local pos = self:getParent():convertToWorldSpace(self:getPositionLua())
	pos = self.world:convertToNodeSpace(pos)
	self.world.scoreLabel:setPosition(pos.x, pos.y)
	self.world.scoreLabel:runAction(CCFadeTo:create(1, 0))
	self.world.shuangbei = 2 * self.world.shuangbei
end

function GeZi:create(lingdangFile, factory, lingdang)
	local newLingDang = lingdang or GeZi:new()
	newLingDang.factory = factory
	newLingDang.world = factory.world
	
	local cc2dNode = CC2DFileCache:sharedCC2DFileCache():addCC2DNode(lingdangFile)
	local ccLingDang = tolua.cast(cc2dNode:createCCNode(factory), "CCSprite")
	
	lingdangCount = lingdangCount + 1
	newLingDang.lingdangID = lingdangCount
	Misc:setNodeName(ccLingDang, "lingdang" .. lingdangCount)
	
	tolua.setpeer(ccLingDang, newLingDang)
	
	local function onEnterOrExit(eventType)
		if eventType == kCCNodeOnExit then
			ccLingDang:onExit()
		else
			ccLingDang:onEnter()
		end
	end
	
	ccLingDang:registerScriptHandler(onEnterOrExit)
	
	if ccLingDang:isRunning() then
		ccLingDang:onEnter()
	end
	return ccLingDang
end